#!/bin/bash

# 20240X LIFUBING CHANGE FOR OPENEULER 24.03 RELEASE
# OpenEuler 24.03环境下AGIROS安装脚本
# 支持两个命令行参数：1.AGIROS_VERSION，默认值为2512,可以指定为2506、2512其中之一，2.RELEASE_TYPE，默认值release，可以指定为release或dailybuild
# 示例：. install.sh 2512 release
# 示例：. install.sh 2512 dailybuild
# 示例：. install.sh


# ===== 配置参数 =====
REPO_URL="http://1.94.193.239/yumrepo/agiros/openeuler2403lts"
# 从命令行参数获取AGIROS_VERSION，如果没有提供则使用默认值2512
AGIROS_VERSION=${1:-2512}
# 从命令行参数获取RELEASE_TYPE，如果没有提供则使用默认值release
RELEASE_TYPE=${2:-release}
AGIROS_DEP_URL="http://1.94.193.239/yumrepo/agiros/agirosdep/agirosdep-0.25.1-py3-none-any.whl"
REPO_CONFIG_PATH="/etc/yum.repos.d/agiros.repo"

# 彩色输出定义
COLOR_RED="\033[31m"
COLOR_GREEN="\033[32m"
COLOR_RESET="\033[0m"

# 验证AGIROS_VERSION参数
if [[ "$AGIROS_VERSION" != "2506" && "$AGIROS_VERSION" != "2512" ]]; then
    echo -e "${COLOR_RED}错误：AGIROS_VERSION必须为2506或2512之一${COLOR_RESET}" >&2
    exit 1
fi

# 验证RELEASE_TYPE参数
if [[ "$RELEASE_TYPE" != "release" && "$RELEASE_TYPE" != "dailybuild" ]]; then
    echo -e "${COLOR_RED}错误：RELEASE_TYPE必须为release或dailybuild${COLOR_RESET}" >&2
    exit 1
fi

SUDO=''
if [ "$(id -u)" -ne 0 ]; then
    SUDO='sudo'
fi
echo -e "${COLOR_GREEN}[AGIROS一键安装向导-OpenEuler 24.03]${COLOR_RESET}"
echo -e "${COLOR_GREEN}使用AGIROS版本: ${AGIROS_VERSION}${COLOR_RESET}"
echo -e "${COLOR_GREEN}使用发布类型: ${RELEASE_TYPE}${COLOR_RESET}"

# 获取OpenEuler的版本信息
echo "检测系统版本..."
OPENEULER_VERSION=$(cat /etc/openEuler-release | grep -oP '\d+\.\d+')
ARCH=$(uname -m)

case "$ARCH" in
    x86_64) 
        echo "CPU架构 X86_64, OpenEuler版本: $OPENEULER_VERSION"
        repo_arch="x86_64"
        ;;
    aarch64) 
        echo "CPU架构 ARM64, OpenEuler版本: $OPENEULER_VERSION"
        repo_arch="aarch64"
        ;;
    riscv64) 
        echo "CPU架构 RISC-V, OpenEuler版本: $OPENEULER_VERSION"
        repo_arch="riscv64"
        ;;
    *)
        echo -e "${COLOR_RED}❌ 当前仅支持x86_64/aarch64/riscv64,检测到不支持的架构: $ARCH${COLOR_RESET}" >&2
        exit 1
        ;;
esac

if [[ "$OPENEULER_VERSION" != "24.03" ]]; then
    echo -e "${COLOR_RED}💡 AGIROS 的 OpenEuler 正式发布版本为 24.03，与当前系统版本不对应${COLOR_RESET}" >&2
    exit 1
fi

check_setup_bash() {
    local ros_distro_list=("melodic" "noetic" "foxy" "humble")
    local agiros_distro_list=("loong")
    local found_ros=0
    local found_agiros=0

    for distro in "${ros_distro_list[@]}"; do
        local setup_file="/opt/ros/${distro}/setup.bash"
        if [ -f "$setup_file" ]; then
            echo -e "${COLOR_RED}💡检测到 ros2 $distro, 脚本: $setup_file ${COLOR_RESET}"
            found_ros=1
        fi
    done

    for distro in "${agiros_distro_list[@]}"; do
        local setup_file="/opt/agiros/${distro}/setup.bash"
        if [ -f "$setup_file" ]; then
            echo -e "${COLOR_RED}💡检测到 agiros $distro, 脚本: $setup_file ${COLOR_RESET}"
            found_agiros=1
        fi
    done

    # 如果最终都没找到
    if [ $found_agiros -eq 0 ]; then
        echo -e "${COLOR_GREEN}💡当前系统未安装AGIROS ${COLOR_RESET}" >&2
    fi
}

echo "检测当前系统是否安装AGIROS..."
check_setup_bash

# 确保直接从终端读取输入
if [ -t 0 ]; then
    # 标准输入是终端，直接读取
    echo "---------AGIROS安装菜单-----------"
    echo -e "${COLOR_GREEN}1. ${COLOR_RESET}安装ros-base和开发工具"
    echo "2. 安装desktop和开发工具"
    echo "3. 安装desktop-full和开发工具"
    echo "4. 清理AGIROS环境"
    echo "5. 退出"
    read -p "请输入数字 (1/2/3/4/5): " choice
else
    # 标准输入不是终端，尝试从 /dev/tty 读取
    echo "----------AGIROS安装菜单----------"
    echo -e "${COLOR_GREEN}1. ${COLOR_RESET}安装ros-base和开发工具"
    echo "2. 安装desktop和开发工具"
    echo "3. 安装desktop-full和开发工具"
    echo "4. 清理AGIROS环境"
    echo "5. 退出"
    read -p "请输入数字 (1/2/3/4/5): " choice </dev/tty
fi

if [[ -z "$choice" ]]; then
    echo -e "${COLOR_RED}错误：未输入任何内容${COLOR_RESET}" >&2
    exit 1
fi
echo "用户输入了：$choice"

# 验证输入是否为0-7的数字
if ! [[ "$choice" =~ ^[0-7]$ ]]; then
    echo -e "${COLOR_RED}错误：无效的选择，请输入0-7之间的数字${COLOR_RESET}" >&2
    exit 1
fi

init() {
    # 检查当前时区是否已经正确设置
    CURRENT_TIMEZONE=$(readlink /etc/localtime 2>/dev/null || echo "")
    EXPECTED_TIMEZONE="/usr/share/zoneinfo/Asia/Shanghai"

    if [[ "$CURRENT_TIMEZONE" == "$EXPECTED_TIMEZONE" ]]; then
        echo "时区已正确设置为 Asia/Shanghai，跳过设置"
    else
        # 检查并安装 tzdata（如果缺失）
        if ! rpm -q tzdata &> /dev/null; then
            echo "tzdata 包未找到，正在安装..."
            $SUDO dnf install -y tzdata
        fi
        
        # 设置时区为 Asia/Shanghai
        echo "设置时区为 Asia/Shanghai..."
        $SUDO ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
        $SUDO echo "Asia/Shanghai" > /etc/timezone
    fi

    # 添加 YUM 源
    echo "配置软件仓库源..."
    $SUDO tee $REPO_CONFIG_PATH >/dev/null <<EOL

[agiros-main-packages]
name=agiros-main-packages
baseurl=http://1.94.193.239/yumrepo/agiros/openeuler2403lts/$AGIROS_VERSION/$repo_arch/$RELEASE_TYPE
enabled=1
gpgcheck=0

[agiros-third-packages]
name=agiros-third-packages
baseurl=http://1.94.193.239/yumrepo/agiros/openeuler2403lts/$AGIROS_VERSION/\$basearch/3-party
enabled=1
gpgcheck=0
EOL

    # 更新缓存
    echo "更新软件包列表..."
    dnf clean all
    if ! $SUDO dnf makecache; then
        echo -e "${COLOR_RED}更新软件包列表失败${COLOR_RESET}" >&2
        exit 1
    fi
}

# 配置环境变量
configure_environment_variable() {
    env_var_dir="/opt/agiros/loong"
    bashrc_path="$HOME/.bashrc"
    setup_bash="/opt/agiros/loong/setup.bash"

    if [ -f "$setup_bash" ]; then
        echo "找到 AGIROS 环境配置文件: $setup_bash"
    else
        echo -e "${COLOR_RED}❌ 错误：未找到 AGIROS setup.bash 文件，请确认是否已安装 AGiROS${COLOR_RESET}" >&2
        exit 1
    fi
    
    # 添加环境变量
    env_var_key="export PATH=$env_var_dir:\$PATH"
    if ! grep -qF "$env_var_key" "$bashrc_path"; then
        if ! echo -e "\n$env_var_key\n" >> "$bashrc_path"; then
            echo "写入环境变量失败"
            exit 1
        fi
        echo "✅ 环境变量已成功添加到 $bashrc_path"
    else
        echo "💡 环境变量已存在于 $bashrc_path 中"
    fi
    
    # 添加AGIROS Loong环境配置
    source /opt/agiros/loong/setup.bash

    if ! grep -qF "source $setup_bash" "$bashrc_path"; then
        if ! echo "source $setup_bash" >> "$bashrc_path"; then
            echo "添加AGIROS Loong环境配置到 $bashrc_path 失败"
            exit 1
        fi
        echo "已将 source $setup_bash 添加到 $bashrc_path"
    else
        echo "source $setup_bash 已存在于 $bashrc_path 中"
    fi
    
    source $bashrc_path
    echo "💡 已执行 'source $bashrc_path' 使环境变量生效"
}

# ===== 清理缓存函数（新增）=====
clean_cache() {
    echo -e "\n\033[1;33m===== 清理系统缓存 =====\033[0m"
    
    # 清理dnf缓存
    echo "1. 清理dnf缓存..."
    $SUDO dnf clean all
    $SUDO rm -rf /var/cache/dnf/*

    echo "2. 修正dnf可能的错误"
    $SUDO dnf makecache
    $SUDO dnf check-update
}

# ===== 删除现有配置 =====
cleanup_system() {
    echo -e "\n\033[1;33m===== 清理现有配置 =====\033[0m"
    
    # 删除仓库配置
    echo "移除仓库配置文件 $REPO_CONFIG_PATH"
    $SUDO rm -f "$REPO_CONFIG_PATH"

    # 调用缓存清理函数（新增）
    clean_cache

    echo -e "\n\033[1;32m✔ 所有仓库配置和系统缓存已成功移除\033[0m"
}

# 安装开发工具
install_tools() {
    echo "💡 安装开发工具和依赖..."
    $SUDO dnf install -y \
        make \
        cmake \
        gcc \
        gcc-c++ \
        curl \
        vim \
        nano \
        git \
        python3 \
        python3-devel \
        python3-flake8 \
        python3-pytest-cov \
        python3-pip \
        python3-setuptools \
        zbar-devel \

    # 安装额外的Python工具
    echo "安装额外的Python工具..."

    #安装colcon相关工具
    pip3 install -U -i https://pypi.tuna.tsinghua.edu.cn/simple \
        colcon-common-extensions \
        colcon-mixin \

    # 检查pip版本并相应调整安装命令
    PIP_VERSION=$(pip3 --version | awk '{print $2}' | cut -d. -f1)

    if [ "$PIP_VERSION" -ge 23 ]; then
        # 新版本pip使用 --break-system-packages
        pip3 install -U -i https://pypi.tuna.tsinghua.edu.cn/simple \
            argcomplete \
            pytest-repeat \
            pytest-rerunfailures \
            --break-system-packages
    else
        # 旧版本pip不需要 --break-system-packages
        pip3 install -U -i https://pypi.tuna.tsinghua.edu.cn/simple \
            argcomplete \
            pytest-repeat \
            pytest-rerunfailures
    fi

    echo "配置并初始化agirosdep..."
    if [ ! -f "/etc/agiros/agirosdep/sources.list.d/20-default.list" ]; then
        pip install $AGIROS_DEP_URL

        # 初始化rosdep
        $SUDO agirosdep init || true

        # 更新rosdep
        echo "更新agirosdep..."
        agirosdep update
    fi
}

install_package() {
    local install_mode="$1"
    local package_name=""
    
    case $install_mode in
        1) 
            init
            package_name="agiros-loong-ros-base agiros-loong-turtlesim"
            ;;
        2) 
            init
            package_name="agiros-loong-desktop agiros-loong-turtlesim"
            ;;
        3) 
            init
            package_name="agiros-loong-desktop-full agiros-loong-turtlesim"
            ;;
        4) 
            cleanup_system
            exit 0
            ;;
        5) 
            echo "正常退出脚本"
            exit 0
            ;;
        *)
            echo "输入错误，请输入1-5"
            exit 1
            ;;
    esac
    
    echo "开始安装 $package_name ..."
    if ! $SUDO dnf install -y $package_name; then
        echo "💡 安装失败，尝试修复依赖..."
        
        # 尝试使用 --allowerasing 选项修复依赖
        if ! $SUDO dnf install -y --allowerasing $package_name; then
            echo -e "${COLOR_RED}❌ 依赖修复失败，请手动处理${COLOR_RESET}" >&2
            exit 1
        fi
    fi

    echo "配置环境变量..."
    configure_environment_variable   

    $SUDO dnf clean all
    echo -e "${COLOR_GREEN}✅ $package_name 安装成功！${COLOR_RESET}"

    echo "安装开发工具..."
    install_tools

    # 验证安装
    echo "验证AGIROS安装..."
    if command -v agiros &> /dev/null; then
        echo "✅ AGIROS已安装成功"
    else
        echo "agiros 命令未找到，可能需要重新启动终端或手动source环境变量"
        echo "请运行: source $bashrc_path"
    fi
}

install_package "$choice"
